<template>
	<div class="host">
		<div class="box">
			<div class="content">
				<div class="chartRef" style="position: relative; flex: 1; height: 100%" v-loading="load"
					v-for="(model, index) in modelList" :key="index">
					<div :ref="sethostLineChartRef" style="flex: 1"></div>
				</div>
			</div>
		</div>
		
			<div style="margin: auto">
					<div style="width: 600px">
						<el-slider
							v-if="index != -1 && index != modelList.length - 1"
							v-model="maxValue"
							range
							:max="800"
							@change="szz()"></el-slider>
					</div>
				</div>
	</div>
</template>

<script setup>
	import {
		http
	} from '@/api/http.js'
	import labTable from '@/mixins/table.json'
	import {
		chunk
	} from '@/utils/utils.js'
	import {
		ENGINE_LEFT,
		ENGINE_RIGHT,
		ENGINE_LEFT_PW,
		ENGINE_RIGHT_PW,
		ENGINE_LEFT_ZC,
		ENGINE_RIGHT_ZC,
		ZC_LEN,
		PW_LEN,
		ENGINE_LEFT_SUPERCHARGER,
		ENGINE_RIGHT_SUPERCHARGER,
		ENGINE_LEFT_INFO,
		ENGINE_RIGHT_INFO,
		SUPERCHARGER_LEN,
		ENGINE_HYB_PW1,
		ENGINE_HYB_PW2,
		ENGINE_HYB_PW3,
		ENGINE_HYB_PW4,
		ENGINE_HYB_PW5,
		ENGINE_HYB_PW6,
		INFO,
		TF
	} from '@/utils/const.js'
	import moment from 'moment'
	import dataJson from '@/mixins/data.json'
	import {
		ref,
		reactive,
		onMounted,
		onUnmounted,
		watch,
		markRaw,
		inject,
	} from 'vue'
	import echarts from "@/echarts/index.js";
	import { onLoad } from '@dcloudio/uni-app';
	let load = ref(true)
	let dateTime = ref(moment().format('YYYY-MM-DD HH:mm:ss'))


	let leftFields = {
		sup_fields: ENGINE_LEFT_SUPERCHARGER,
		info_fields: ENGINE_LEFT_INFO,
		zc_fields: ENGINE_LEFT_ZC,
		pw_fields: ENGINE_LEFT_PW,
		fields: [...ENGINE_LEFT_PW, ...ENGINE_LEFT_ZC, ...ENGINE_LEFT_SUPERCHARGER, ...ENGINE_LEFT_INFO]
	}
	let rightFields = {
		sup_fields: ENGINE_RIGHT_SUPERCHARGER,
		info_fields: ENGINE_RIGHT_INFO,
		zc_fields: ENGINE_RIGHT_ZC,
		pw_fields: ENGINE_RIGHT_PW,
		fields: [...ENGINE_RIGHT_PW, ...ENGINE_RIGHT_ZC, ...ENGINE_RIGHT_SUPERCHARGER, ...ENGINE_RIGHT_INFO]
	}
	let hby = {
		hbyfields1: ENGINE_HYB_PW1,
		hbyfields2: ENGINE_HYB_PW2,
		hbyfields3: ENGINE_HYB_PW3,
		hbyfields4: ENGINE_HYB_PW4,
		hbyfields5: ENGINE_HYB_PW5,
		hbyfields6: ENGINE_HYB_PW6,
		fields: [...ENGINE_HYB_PW1, ...ENGINE_HYB_PW2, ...ENGINE_HYB_PW3, ...ENGINE_HYB_PW4, ...ENGINE_HYB_PW5, ...
			ENGINE_HYB_PW6
		]
	}
	let fields = [leftFields, rightFields, hby]
	let labTableList = [labTable.left_main, labTable.right_main, labTable.hyb]
	let props = ref(0)
	let engine = ref(INFO[props.value])
	let fieldsList = ref(fields[props.value])
	let fieldData = ref(labTableList[props.value])

	
	onLoad((options) => {
	props.value = options.props
	});
	// 使用函数生成时间段
	// import dataJson from "@/mixins/test.json"
	let Echarts = echarts
	let allData = inject('allData')
	let instanceEchartsList = ref([])
	const hostLineChartRef = ref([])
	const index = ref(-1)
	const fieldKey = ref(-1)

	let timeInterval = ref([5, 10, 15, 30])
	let grid = [{
			left: '10%',
			right: '8%',
			height: '50%'
		},
		{
			left: '10%',
			right: '8%',
			top: '63%',
			height: '16%'
		}
	]
	const setSubGraphic = ({
		fields,
		boxWidth
	}) => {
		let fieldflat = fields.flat()
		return fieldflat.map((item, i) => {
			return {
				type: 'text',
				left: `${boxWidth ? boxWidth[i] : i * 100}` // 第一个字符的位置
				// style: {
				// 	fill: '#409EFF',
				// 	text: fieldData.value[item].name.substr(3),
				// 	textFill: '#fff',
				// 	fontSize: 14,
				// 	textAlign: 'center',
				// 	textVerticalAlign: 'middle'
				// },
				// onclick: function () {
				// 	routerPush(`/histroy/pw/${engine.value}/${item}`)
				// }
			}
		})
	}

	let model1 = fieldsList.value.pw_fields ?
		[{
				title: '排气温度',
				fields: [...chunk(fieldsList.value.pw_fields, 3)],
				minutes: timeInterval.value[0],
				data: [],
				max: 800,
				waningValue: 530,
				graphic: {
					top: '6.7%',
					subGraphic: {
						type: 'group',
						bottom: '7.5%',
						left: '7.5%',
						children: setSubGraphic({
							fields: [...chunk(fieldsList.value.pw_fields, 3)]
						})
					}
				},
				dataZoom: {
					top: '85%'
				},
				grid: [{
						left: '10%',
						top: '12%',
						right: '8%',
						height: '28%'
					},
					{
						left: '10%',
						right: '8%',
						top: '45%',
						height: '28%'
					},
					{
						left: '10%',
						right: '8%',
						bottom: '16.5%',
						height: '15%'
					}
				]
			},
			{
				title: '轴承温度',
				fields: [...chunk(fieldsList.value.zc_fields, 4)],
				minutes: timeInterval.value[0],
				data: [],
				max: 150,
				waningValue: 95,
				graphic: {
					top: '6.7%',
					subGraphic: {
						type: 'group',
						left: 'center',
						bottom: '7.5%',
						children: setSubGraphic({
							fields: [...chunk(fieldsList.value.zc_fields, 4)]
						})
					}
				},
				dataZoom: {
					top: '85%'
				},
				grid: [{
						left: '10%',
						top: '12%',
						right: '8%',
						height: '28%'
					},
					{
						left: '10%',
						right: '8%',
						top: '45%',
						height: '28%'
					},
					{
						left: '10%',
						right: '8%',
						bottom: '16.5%',
						height: '15%'
					}
				]
			},
			{
				title: '增压器',
				fields: fieldsList.value.sup_fields,
				minutes: timeInterval.value[0],
				data: fieldsList.sup_fields,
				dataZoom: {
					top: '76%'
				},
				grid: [{
						top: '22%',
						left: '10%',
						right: '8%',
						height: '37%'
					},
					{
						left: '10%',
						right: '8%',
						top: '57%',
						height: '16%'
					}
				],
				graphic: {
					top: '13%',
					subGraphic: {
						type: 'group',
						bottom: '12.5%',
						left: '3%',
						children: setSubGraphic({
							fields: fieldsList.value.sup_fields,
							boxWidth: ['0', '100', '200', '300', '405', '555']
						})
					}
				}
			},
			{
				title: '主机信息',
				fields: fieldsList.value.info_fields,
				minutes: timeInterval.value[0],
				data: fieldsList.info_fields,
				dataZoom: {
					top: '76%'
				},
				grid: [{
						top: '22%',
						left: '10%',
						right: '8%',
						height: '37%'
					},
					{
						left: '10%',
						right: '8%',
						top: '57%',
						height: '16%'
					}
				],
				graphic: {
					top: '13%',
					subGraphic: {
						type: 'group',
						left: 'center',
						bottom: '8.7%',
						children: setSubGraphic({
							fields: fieldsList.value.info_fields
						})
					}
				}
			}
		] :
		[]
	let model2 = fieldsList.value.hbyfields1 ?
		[{
				title: '1#货油泵',
				fields: [...chunk(fieldsList.value.hbyfields1, 4)],
				minutes: timeInterval.value[0],
				data: [],
				waningValue: 530,
				graphic: {
					top: '6.7%',
					subGraphic: {
						type: 'group',
						bottom: '7.5%',
						left: '7.5%',
						children: setSubGraphic({
							fields: [...chunk(fieldsList.value.hbyfields1, 4)]
						})
					}
				},
				dataZoom: {
					top: '85%'
				},
				grid: [{
						left: '10%',
						top: '12%',
						right: '8%',
						height: '28%'
					},
					{
						left: '10%',
						right: '8%',
						top: '45%',
						height: '28%'
					},
					{
						left: '10%',
						right: '8%',
						bottom: '16.5%',
						height: '15%'
					}
				]
			},

			{
				title: '2#货油泵',
				fields: [...chunk(fieldsList.value.hbyfields2, 4)],
				minutes: timeInterval.value[0],
				data: [],
				waningValue: 530,
				graphic: {
					top: '6.7%',
					subGraphic: {
						type: 'group',
						bottom: '7.5%',
						left: '7.5%',
						children: setSubGraphic({
							fields: [...chunk(fieldsList.value.hbyfields2, 4)]
						})
					}
				},
				dataZoom: {
					top: '85%'
				},
				grid: [{
						left: '10%',
						top: '12%',
						right: '8%',
						height: '28%'
					},
					{
						left: '10%',
						right: '8%',
						top: '45%',
						height: '28%'
					},
					{
						left: '10%',
						right: '8%',
						bottom: '16.5%',
						height: '15%'
					}
				]
			},
			{
				title: '3#货油泵',
				fields: [...chunk(fieldsList.value.hbyfields3, 4)],
				minutes: timeInterval.value[0],
				data: [],
				waningValue: 530,
				graphic: {
					top: '6.7%',
					subGraphic: {
						type: 'group',
						bottom: '7.5%',
						left: '7.5%',
						children: setSubGraphic({
							fields: [...chunk(fieldsList.value.hbyfields3, 4)]
						})
					}
				},
				dataZoom: {
					top: '85%'
				},
				grid: [{
						left: '10%',
						top: '12%',
						right: '8%',
						height: '28%'
					},
					{
						left: '10%',
						right: '8%',
						top: '45%',
						height: '28%'
					},
					{
						left: '10%',
						right: '8%',
						bottom: '16.5%',
						height: '15%'
					}
				]
			},
			{
				title: '扫舱泵',
				fields: [...chunk(fieldsList.value.hbyfields4, 3)],
				minutes: timeInterval.value[0],
				data: [],
				waningValue: 530,
				graphic: {
					top: '6.7%',
					subGraphic: {
						type: 'group',
						bottom: '7.5%',
						left: '7.5%',
						children: setSubGraphic({
							fields: [...chunk(fieldsList.value.hbyfields4, 3)]
						})
					}
				},
				dataZoom: {
					top: '85%'
				},
				grid: [{
						left: '10%',
						top: '12%',
						right: '8%',
						height: '28%'
					},
					{
						left: '10%',
						right: '8%',
						top: '45%',
						height: '28%'
					},
					{
						left: '10%',
						right: '8%',
						bottom: '16.5%',
						height: '15%'
					}
				]
			},
			{
				title: '1#压载泵',
				fields: [...chunk(fieldsList.value.hbyfields5, 3)],
				minutes: timeInterval.value[0],
				data: [],
				waningValue: 530,
				graphic: {
					top: '6.7%',
					subGraphic: {
						type: 'group',
						bottom: '7.5%',
						left: '7.5%',
						children: setSubGraphic({
							fields: [...chunk(fieldsList.value.hbyfields5, 3)]
						})
					}
				},
				dataZoom: {
					top: '85%'
				},
				grid: [{
						left: '10%',
						top: '12%',
						right: '8%',
						height: '28%'
					},
					{
						left: '10%',
						right: '8%',
						top: '45%',
						height: '28%'
					},
					{
						left: '10%',
						right: '8%',
						bottom: '16.5%',
						height: '15%'
					}
				]
			},
			{
				title: '2#压载泵',
				fields: [...chunk(fieldsList.value.hbyfields6, 3)],
				minutes: timeInterval.value[0],
				data: [],
				waningValue: 530,
				graphic: {
					top: '6.7%',
					subGraphic: {
						type: 'group',
						bottom: '7.5%',
						left: '7.5%',
						children: setSubGraphic({
							fields: [...chunk(fieldsList.value.hbyfields6, 3)]
						})
					}
				},
				dataZoom: {
					top: '85%'
				},
				grid: [{
						left: '10%',
						top: '12%',
						right: '8%',
						height: '28%'
					},
					{
						left: '10%',
						right: '8%',
						top: '45%',
						height: '28%'
					},
					{
						left: '10%',
						right: '8%',
						bottom: '16.5%',
						height: '15%'
					}
				]
			}
		] :
		[]
	let models = [model1, model1, model2]

	let modelList = reactive(models[props.value])

	const getLocalUTCDate = ({
		date,
		minutes
	}) => {
		let data = moment(dateTime.value)
		return {
			start: data.clone().subtract(minutes, 'minutes').clone().utc().format(),
			stop: data.clone().clone().utc().format()
		}
	}

	let parmas = reactive({
		measurementName: engine.value,
		...getLocalUTCDate({
			minutes: timeInterval.value[1]
		}),
		fields: fieldsList.value.fields.join('_'),
		bucketName: localStorage.getItem('bucketName')
	})

	let data = ref(null)
	let setLegend = (model, isarry) => {
		let data = []
		let {
			fields
		} = model
		if (isarry) {
			fields.forEach((arr, i) => {
				arr.forEach((item) => {
					data.push(fieldData.value[item].name)
				})
			})
		} else {
			data = fields.map((item) => fieldData.value[item]?.name)
		}
		data.push('Volume')
		return data
	}


	let setTitle = (model) => {
		let {
			title
		} = model
		return {
			show: true,
			left: 'center',
			text: title + '(' + dateTime.value + ')'
			// subtext: dateTime.value
		}
	}

	let setgraphic = (graphic, i) => {
		return [{
				type: 'rect',
				left: '15%',
				top: graphic?.top ?? '14%',
				shape: {
					width: 50,
					height: 25
				},
				style: {
					fill: '#409EFF',
					text: '5分钟',
					textFill: '#fff',
					fontSize: 14,
					textAlign: 'center',
					textVerticalAlign: 'middle'
				},
				onclick: async function(item) {
					await onClick(timeInterval.value[0], i)
				}
			},
			{
				type: 'rect',
				left: '30%',
				top: graphic?.top ?? '14%',
				shape: {
					width: 50,
					height: 25
				},
				style: {
					fill: '#409EFF',
					text: '10分钟',
					textFill: '#fff',
					fontSize: 14,
					textAlign: 'center',
					textVerticalAlign: 'middle'
				},
				onclick: async function(item) {
					console.log('月按钮被点击了！')
					await onClick(timeInterval.value[1], i)
				}
			},
			{
				type: 'rect',
				left: '45%',
				top: graphic?.top ?? '14%',
				shape: {
					width: 50,
					height: 25
				},
				style: {
					fill: '#409EFF',
					text: '15分钟',
					textFill: '#fff',
					fontSize: 14,
					textAlign: 'center',
					textVerticalAlign: 'middle'
				},
				onclick: async function() {
					await onClick(timeInterval.value[2], i)
				}
			},
			{
				type: 'rect',
				left: '60%',
				top: graphic?.top ?? '14%',
				shape: {
					width: 50,
					height: 25
				},
				style: {
					fill: '#409EFF',
					text: '30分钟',
					textFill: '#fff',
					fontSize: 14,
					textAlign: 'center',
					textVerticalAlign: 'middle'
				},
				onclick: async function() {
					await onClick(timeInterval.value[3], i)
				}
			},
			{
				...graphic?.subGraphic
			}
			// subGraphic
		]
	}

	let setOption = ({
		model,
		data,
		index
	}) => {
		let len = model.fields.length
		let max = model.max
		let min = model.min
		let isarry = Array.isArray(model.fields[0])
		let realation_arr = new Array(len + 1).fill().map((item, i) => i)
		let real_realation = new Array(len).fill().map((item, i) => i)

		return {
			title: setTitle(model),
			animation: false,
			legend: {
				bottom: 10,
				left: 'center',
				data: setLegend(model, isarry)
			},
			graphic: setgraphic(model.graphic, index),
			tooltip: {
				 extraCssText: 'z-index: 9999;', 
				trigger: 'axis',
	
				confine: true, // 确保 tooltip 不会超出图表容器
				axisPointer: {
					show: true,
					type: 'cross'
				},
				borderWidth: 1,
				borderColor: '#ccc',
				padding: 10,
				textStyle: {
					color: '#000'
				},
				position: function(pos, params, el, elRect, size) {
					const obj = {
						top: 10
					}
					obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30
					return obj
				}
				// extraCssText: 'width: 170px'
			},
			axisPointer: {
				link: [{
					xAxisIndex: 'all'
				}],
				label: {
					backgroundColor: '#777'
				}
			},
			brush: {
				xAxisIndex: 'all',
				brushLink: 'all',
				outOfBrush: {
					colorAlpha: 0.1
				}
			},
			grid: model?.grid || grid,
			xAxis: [
				...setxAxis(real_realation, data, isarry),
				{
					type: 'category',
					gridIndex: isarry ? len : 1,
					data: data.categoryData,
					boundaryGap: false,
					axisLine: {
						onZero: true
					},
					axisTick: {
						show: false
					},
					splitLine: {
						show: false
					},
					axisLabel: {
						show: false
					},
					min: 'dataMin',
					max: 'dataMax'
				}
			],
			yAxis: [
				...setyAxis(real_realation, isarry, max, min),
				{
					scale: true,
					gridIndex: isarry ? len : 1,
					splitNumber: 2,
					axisLabel: {
						show: false
					},
					axisLine: {
						show: false
					},
					axisTick: {
						show: false
					},
					splitLine: {
						show: false
					}
				}
			],
			dataZoom: [
				// {
				// 	// rangeMode: 'value',
				// 	type: 'inside',
				// 	xAxisIndex: realation_arr,
				// 	start: 100,
				// 	end: 0
				// 	// minValueSpan: 1 * 60 * 1000,
				// 	// maxValueSpan: 5 * 60 * 1000
				// },
				// {
				// 	show: true,
				// 	xAxisIndex: realation_arr,
				// 	type: 'slider'
				// 	// ...model.dataZoom
				// 	// startValue: '2024-06-21 23:30:09',
				// 	// endValue: '2024-06-21 23:58:56'
				// 	// start: '2004-01-02"',
				// 	// end: '2004-01-05',
				// 	// maxValueSpan: 3600 * 24 * 1000,
				// 	// minValueSpan: 3600 * 24 *  1000
				// }
			],
			series: [...setSeries(model, data), {
				...setbarSeries(isarry ? len : 1, data.volumns, model)
			}]
		}
	}


	function tranlateData(rawData) {
		let obj = {}
		rawData.forEach((element) => {
			if (!obj[element._time]) {
				obj[element._time] = []
			}
			if (obj[element._time].length) return
			let firstRaw = rawData
				.filter((item) => item._time == element._time)
				.sort((a, b) => {
					let filedANumber = a._field.slice(1)
					let filedBNumber = b._field.slice(1)
					if (filedBNumber > filedANumber) return -1
				})
				.map((item) => (item = item._value))
			let time = utcTranLocalTime(element._time)
			obj[element._time].push(...[time, ...firstRaw])
		})
		return Object.values(obj)
	}



	function splitData(data) {
		var categoryData = []
		var values = []
		var volumns = []
		for (var i = 0; i < data.length; i++) {
			categoryData.push(data[i][0]) // 假设日期是第一个元素
			values.push(data[i]) // 开盘、最高、最低、收盘价
			volumns.push([data[i][0], 1000]) // 第六个元素是交易量
		}
		return {
			categoryData: categoryData,
			values: values,
			volumns: volumns
		}
	}

	function utcTranLocalTime(value, format = 'YYYY-MM-DD HH:mm:ss') {
		return moment.utc(value).local().format('YYYY-MM-DD HH:mm:ss')
	}

	function calculateMA(dayCount, data) {
		let arr = []
		data.categoryData.forEach((item, i) => {
			arr.push([item, data.values[i][dayCount + 1]])
		})
		return arr
	}
	let _xAxis = {
		type: 'time',
		data: data.categoryData,
		boundaryGap: false,
		// minInterval: 1 * 60 * 1000,
		// maxInterval: 60 * 60 * 1000,
		axisLine: {
			onZero: false
		},
		splitLine: {
			show: false
		},
		min: 'dataMin',
		max: 'dataMax',
		axisPointer: {
			link: [{
				xAxisIndex: 'all'
			}],
			show: true,
			z: 100
		},
		axisLine: {
			onZero: true
		},
		gridIndex: 0,
		splitNumber: 4,
		axisLabel: {
			showMaxLabel: true
		}
	}
	const setxAxis = (realation_arr, data, isarry) => {
		let res = []
		if (isarry) {
			realation_arr.forEach((item, i) => {
				let other =
					i % 2 ?
					{
						position: 'top',
						onZero: false,
						axisLine: {
							show: true
						},
						axisTick: {
							show: true,
							inside: false
						}
					} :
					{}
				let defxAxis = {
					..._xAxis,
					data: data.categoryData,
					gridIndex: i,
					...other
				}
				res.push(defxAxis)
			})
		} else {
			let defxAxis = {
				..._xAxis,
				data: data.categoryData,
				gridIndex: 0
			}
			res.push(defxAxis)
		}

		return res
	}
	let _yAxis = {
		gridIndex: 0,
		scale: true,
		splitArea: {
			show: true
		},
		min: 0
	}
	const setyAxis = (realation_arr, isarry, max, min) => {
		console.log(isarry + 'isarry')
		let res = []
		if (isarry) {
			realation_arr.forEach((item, i) => {
				let other = i % 2 ? {
					inverse: true
				} : {}
				let defxAxis = {
					..._yAxis,
					gridIndex: i,
					...other
				}
				if (max) {
					defxAxis.max = max
				}
				if (min) {
					defxAxis.min = min
				}
				res.push(defxAxis)
			})
		} else {
			let defxAxis = {
				..._yAxis,
				gridIndex: 0
			}
			if (max) {
				defxAxis.max = max
			}
			if (min) {
				defxAxis.min = min
			}
			res.push(defxAxis)
		}

		console.log(res, '==============>')

		return res
	}

	let fetchDataList = async () => {
		  try {
		let {
			list
		} = await http('GET')('/getAll', parmas)
		return list
		} catch (error) {
		  console.error('获取数据失败:', error);
		}
	}

	let updateAllCharts = (list) => {
		modelList.forEach((model, i) => {
			let fields = model.fields
			let rowData = tranlateData(splitChatsFilesData(fields, list))
			console.log('modelList[i].data', rowData)
			modelList[i].data = rowData
			let data = splitData(rowData)
			setCharts(hostLineChartRef.value[i], i, data)
		})
	}
	import {
		version
	} from 'vue';
	onMounted(async () => {

		load.value = true
		let list = await fetchDataList()
		updateAllCharts(list)
		load.value = false
	})
	onUnmounted(() => {
		const detectZoom = () => {
			let ratio = 0,
				screen = window.screen,
				ua = navigator.userAgent.toLowerCase()
			if (window.devicePixelRatio !== undefined) {
				ratio = window.devicePixelRatio
			} else if (~ua.indexOf('msie')) {
				if (screen.deviceXDPI && screen.logicalXDPI) {
					ratio = screen.deviceXDPI / screen.logicalXDPI
				}
			} else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
				ratio = window.outerWidth / window.innerWidth
			}
			if (ratio) {
				ratio = Math.round(ratio * 100)
			}
			document.body.style.zoom = 80 / Number(ratio)
			return ratio
		}
		if (routeZ.path.indexOf('/histroy/pw') == -1) {
			detectZoom()
		}
	})

	const splitChatsFilesData = (fields, data) => {
		console.log('splitChatsFilesData', fields.flat())
		return data.filter((item) => fields.flat().includes(item._field))
	}

	// _field _time _value
	const wsGenerateData = ({
		fields,
		data,
		utcDate
	}) => {
		let row = []
		if (Array.isArray(fields[0])) {
			fields.forEach((field) => {
				field.forEach((item) => {
					row.push({
						_field: item,
						_time: utcDate,
						_value: data[item].currentValue
					})
				})
			})
		} else {
			row = fields.map(
				(item) => (item = {
					_field: item,
					_time: utcDate,
					_value: data[item].currentValue
				})
			)
		}
		return row
	}

	const setLineSeries = (i) => {
		return {
			name: '',
			type: 'line',
			endLabel: {
				show: true,
				formatter: function(params) {
					let {
						data
					} = params
					//moment(data[0]).format('HH:mm:ss') + ': ' +
					return data[1]
				}
			},
			markLine: {
				silent: true,
				data: [{
					yAxis: 200,
					lineStyle: {
						color: 'red'
					}
				}]
			},
			xAxisIndex: i,
			yAxisIndex: i,
			data: null,
			smooth: true,
			symbol: 'none',
			lineStyle: {
				opacity: 0.5
			}
		}
	}

	const setbarSeries = (i, volumns, model) => {
		return {
			name: 'Volume',
			type: 'bar',
			symbol: 'none',
			xAxisIndex: i,
			yAxisIndex: i,
			data: volumns,
			itemStyle: {
				color: (params) => {
					return params.value > (model.waningValue || 1000) ? 'red' : 'green'
				}
			}
		}
	}

	const setSeries = (model, data) => {
		let fields = model.fields
		let len = fields.length
		let total = fields.flat().length
		let series = []
		if (Array.isArray(fields[0])) {
			fields.forEach((item, i) => {
				let splitfields = fields[i]
				splitfields.forEach((jitem, j) => {
					let index = i > 0 ? fields[i - 1].length + j : j
					series.push({
						...setLineSeries(i),
						name: fieldData.value[jitem].name,
						data: calculateMA(index, data)
					})
				})
			})
		} else {
			series = fields.map((item, i) => {
				return {
					...setLineSeries(0),
					name: fieldData.value[fields[i]].name,
					data: calculateMA(i, data)
				}
			})
		}
		return series
	}

	const onClick = async (time, i, date) => {
		load.value = true
		modelList[i].minutes = time
		let {
			start,
			stop
		} = getLocalUTCDate({
			minutes: time
		})
		// console.log(
		// 	'=====================[onclick]start,end',
		// 	utcTranLocalTime(start),
		// 	utcTranLocalTime(stop)
		// )
		let data = {
			...parmas,
			start,
			stop,
			fields: modelList[i].fields.flat().join('_')
		}
		parmas = {
			...data
		}
		let list = await fetchDataList()
		let rowData = tranlateData(splitChatsFilesData(modelList[i].fields, list))
		modelList[i].data = rowData
		let row = splitData(rowData)
		setCharts(hostLineChartRef.value[i], i, row)
		load.value = false
	}
	const setCharts = (el, i, rowData) => {
		let model = modelList[i]
		let fields = model.fields
		let option = setOption({
			model,
			data: rowData,
			index: i
		})
		if (instanceEchartsList.value[i]) {
			instanceEchartsList.value[i].setOption(option, true)
			instanceEchartsList.value[i].resize()
		} else {

			instanceEchartsList.value[i] = markRaw(
				Echarts.init(el, null, {
					renderer: 'canvas',
					useDirtyRect: false
				})
			)

			instanceEchartsList.value[i].setOption(option, true)
			instanceEchartsList.value[i].resize()
		}
	}
	// 取出旧数据比较返回最新时间区域段数据
	const compareTimeData = (start, i, nweData) => {
		let rowData = []
		let Data = modelList[i].data
		if (!Data && nweData.length < 1) return false
		let interval = modelList[i].minutes
		let endTime = start
		let startTime = moment(endTime).clone().subtract(interval, 'minute').format('YYYY-MM-DD HH:mm:ss')

		Data.push(...nweData)
		rowData = Data.filter((item) => {
			return item[0] >= startTime
		})
		modelList[i].data = rowData
		return rowData
	}
	const updateCharts = (i, data) => {
		let model = modelList[i]
		let isarry = Array.isArray(model.fields[0])
		let len = model.fields.length
		let real_realation = new Array(len).fill().map((item, i) => i)
		instanceEchartsList.value[i].setOption({
			series: [
				...setSeries(model, data),
				{
					...setbarSeries(isarry ? len : 1, data.volumns, model)
				}
			],
			xAxis: [
				...setxAxis(real_realation, data, isarry),
				{
					type: 'category',
					gridIndex: isarry ? len : 1,
					data: data.categoryData,
					boundaryGap: false,
					axisLine: {
						onZero: true
					},
					axisTick: {
						show: false
					},
					splitLine: {
						show: false
					},
					axisLabel: {
						show: false
					},
					min: 'dataMin',
					max: 'dataMax'
				}
			]
		}, {
			replaceMerge: ['series', 'xAxis']
		})
	}
	


	watch(
		() => allData.value,
		(newVal, oldVal) => {
			document.body.style.zoom = ''
			let {
				start
			} = getLocalUTCDate({
				minutes: 0
			})
			let date = utcTranLocalTime(start)
			let fieldkey = TF[props.value]
			let nodeMap = newVal[fieldkey]
			modelList.map((item, i) => {
				let model = modelList[i]
				let fields = model.fields
				let rowData = tranlateData(wsGenerateData({
					fields,
					data: nodeMap,
					utcDate: start
				}))
				let newrowData = compareTimeData(date, i, rowData)
				if (!newrowData) return
				let data = splitData(newrowData)
				updateCharts(i, data)
			})
		}, {
			deep: true
		}
	)

	let sethostLineChartRef = (el) => {
		hostLineChartRef.value.push(el)
	}
	
</script>
<style scoped lang="scss">
	.host {
		height: 100vh;
		/* 占满整个视口高度 */
		display: flex;
		flex-direction: column;

		.box {
			height: 100%;
			width: 100%;
			display: flex;
			box-sizing: border-box;
			padding: 15px;
		}

		.content {
			width: 100%;
			display: flex;
			flex-direction: column;
			/* 改为纵向排列 */

			.chartRef {
				width: 100%;
				/* 强制占满宽度 */
				min-height: 80vh;
				margin-bottom: 15px;
				/* 添加间距 */
				display: flex;
				flex-direction: column;
			}
		}
	}
</style>